<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <style>

    </style>
</head>

<body>
    <div id="app">
        <table>
            <thead>
                <tr>
                    <th v-for="(title, tidx) in titles" :key="tidx">{{title}}</th>
                    <!-- <th>书籍名称</th>
                    <th>价格</th>
                    <th>出版日期</th>
                    <th>数量</th>
                    <th>操作</th> -->
                </tr>
            </thead>
            <tbody>
                <tr v-for="(book,index) in books" :key="index">
                    <td>{{index}}</td>
                    <td>{{book.name}}</td>
                    <td>{{book.date}}</td>
                    <td>{{book.price}}</td>
                    <td>
                        <button @click="sub(index)">-</button> {{book.num}}
                        <button @click="add(index)">+</button>
                    </td>
                    <td>
                        <button @click="remove(index)">移除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <div>总价格:{{total}}</div>
    </div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            titles: ['编号', '书籍名称', '出版日期', '价格', '数量', '操作'],
            books: [{
                name: '算法导论',
                date: '2006-9',
                price: 85,
                num: 1
            }, {
                name: 'UNIX编程艺术',
                date: '2006-2',
                price: 59,
                num: 1
            }, {
                name: 'Vue程序设计',
                date: '2008-10',
                price: 35,
                num: 1
            }, {
                name: '颈椎康复',
                date: '2006-3',
                price: 129,
                num: 1
            }, ]
        },
        methods: {
            sub(index) {
                if (this.books[index].num <= 0) { //数量不能小于0
                    this.books[index].num = 0
                    return
                }
                this.books[index].num--
            },
            add(index) {
                this.books[index].num++
            },
            remove(index) {
                this.books.splice(index, 1)
            },
        },
        computed: {
            total() {
                return this.books.reduce((prev, current) => {
                    return prev + (current.price * current.num)
                }, 0)
            }
        }
    })
</script>

</html>